package com.link.ppt.View;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.jaiky.imagespickers.ImageConfig;
import com.jaiky.imagespickers.ImageSelector;
import com.jaiky.imagespickers.ImageSelectorActivity;
import com.link.ppt.App.App;
import com.link.ppt.Base.BaseActivity;
import com.link.ppt.Model.Bean.BaseBean;
import com.link.ppt.Model.Bean.SimpleUserInfoBean;
import com.link.ppt.Model.IUserModel;
import com.link.ppt.Model.Impl.UserModelImpl;
import com.link.ppt.R;
import com.link.ppt.Utils.CommonSubscriber;
import com.link.ppt.Utils.DeviceUtils;
import com.link.ppt.Utils.GlideLoader;
import com.link.ppt.Utils.GlideUtils;
import com.link.ppt.Utils.PreferenceUtils;
import com.link.ppt.Utils.RetrofitUploadFileParameterBuilder;
import com.link.ppt.Utils.ToastUtils;

import java.io.File;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.RequestBody;
import rx.functions.Action0;

/**
 * 完善个人信息画面
 * Created by liucxu on 2018/1/23.
 */

public class CompleteUserInfoActivity extends BaseActivity {

    @BindView(R.id.imv_circle_select_header)
    CircleImageView imv_circle_select_header;
    @BindView(R.id.edt_user_name)
    EditText edt_user_name;

    private String mobile;
    private String vericationCode;
    private File avasterFile;

    private IUserModel userModel;

    public static final int REQUEST_CODE = 123;

    @Override
    public int getLayoutId() {
        return R.layout.activity_complete_user_info;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
    }

    @Override
    public void setupData() {
        mobile = getIntent().getStringExtra("mobile");
        vericationCode = getIntent().getStringExtra("code");
        if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(vericationCode)) {
            App.GetInstance().finishActivity(this);
        }
        userModel = new UserModelImpl();
    }

    @OnClick({R.id.imv_circle_select_header, R.id.tv_complete_user_info, R.id.layout_back})
    void doClicks(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.imv_circle_select_header:
                ImageConfig imageConfig = new ImageConfig.Builder(
                        new GlideLoader())
                        .steepToolBarColor(0xff1e3550)
                        .titleBgColor(0xff1e3550)
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启单选   （默认为多选）
                        .singleSelect()
                        // 裁剪 (只有单选可裁剪)
                        .crop(1, 1, 300, 300)
                        // 开启拍照功能 （默认关闭）
                        .showCamera()
                        // 拍照后存放的图片路径（默认 /temp/picture）
                        .filePath("/link_ppt/pic")
                        //设置显示容器
                        .requestCode(REQUEST_CODE)
                        .build();
                ImageSelector.open(CompleteUserInfoActivity.this, imageConfig);
                break;
            case R.id.tv_complete_user_info:
                RegisterUser();
                break;
            case R.id.layout_back:
                App.GetInstance().finishActivity(this);
                break;
        }
    }


    private void RegisterUser() {
        if (TextUtils.isEmpty(edt_user_name.getText().toString())) {
            ToastUtils.showShortToast(CompleteUserInfoActivity.this, getResources().getString(R.string.ppt_string_15));
            return;
        }
        if (avasterFile == null) {
            ToastUtils.showShortToast(CompleteUserInfoActivity.this, getResources().getString(R.string.ppt_string_16));
            return;
        }
        RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
        Map<String, RequestBody> params_requestbody = RetrofitUploadFileParameterBuilder.newBuilder()
                .addParameter("mobile", mobile)
                .addParameter("code", vericationCode)
                .addParameter("userName", edt_user_name.getText().toString())
                .addParameter("task", "register")
                .addParameter("f", "android")
                .addParameter("language", "zh_cn")
                .addParameter("countryCode", PreferenceUtils.GetUserCountryCode())
                .addParameter("version", DeviceUtils.getVersionName())
                .addParameter("userId", PreferenceUtils.GetUserId())
                .addParameter("token", PreferenceUtils.GetUserToken())
                .addParameter("file", avasterFile)
                .bulider();
        userModel.RegisterUser(params_requestbody).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<SimpleUserInfoBean>() {
            @Override
            public void onSuccess(SimpleUserInfoBean response) {
                hideProgress();
                PreferenceUtils.SaveUserToken(response.getDesc());
                PreferenceUtils.SaveUserId(response.getUserId());
                App.GetInstance().finishClassActivity(LoginActivity.class);
                App.GetInstance().finishActivity(CompleteUserInfoActivity.this);
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(CompleteUserInfoActivity.this, response.getDesc());
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
            if ((pathList != null) && (pathList.size() == 1)) {
                avasterFile = new File(pathList.get(0));
                GlideUtils.getInstance().loadSimpleContextVitMap(CompleteUserInfoActivity.this, pathList.get(0), imv_circle_select_header);
            }
        }
    }
}
